package com.czhoujunlv.drug.fragment;

import android.content.ClipData;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.czhoujunlv.drug.Bean.BuyData;
import com.czhoujunlv.drug.Bean.BuyGoods;
import com.czhoujunlv.drug.Bean.LoginData;
import com.czhoujunlv.drug.DBManager.Manager;
import com.czhoujunlv.drug.MainActivity;
import com.czhoujunlv.drug.MyApplication;
import com.czhoujunlv.drug.R;
import com.czhoujunlv.drug.dingdan;
import com.czhoujunlv.drug.toolclass.SpacesItemDecoration;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class BuyFragment extends Fragment {

    RecyclerView item;
    ConstraintLayout submit,delete,editLayout,submitLayout;
    TextView countNum, countPrice,back;
    ImageView edit;
    CheckBox checkBox;
    List<Integer> index = new ArrayList<>();
    BuyGoods buyGoods = new BuyGoods();
    private String res;
    private int size;
    static String token ;
    private List<BuyData> BuyList = new ArrayList<>();
    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    public static final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
            .build();
    private MyAdapter3 myAdapter3 = new MyAdapter3();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user",getActivity().MODE_PRIVATE);
        token = sharedPreferences.getString("token",null) ;
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        //token = sharedPreferences.getString("token",null);
        return inflater.inflate(R.layout.fragment_buy, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        //int test = ((MyApplication) getActivity().getApplication()).getLoginData();
        // EventBus.getDefault().register(this);
        //final SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user",getActivity().MODE_PRIVATE);

        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                Log.i("运行至此处1：", "sdfsdfsdfsdfsd");
                //Log.i("token值：",myApplication.getLoginData().getData().getToken());
                if ( token != null) {
                    Log.i("获得的ID值：", String.valueOf(MainActivity.idCode));
                    try {
                        String s = okPost("http://192.168.43.138:8080/index/getShopGood");
                        Gson gson = new Gson();
                        buyGoods = gson.fromJson(s, BuyGoods.class);
                        BuyList.clear();
                        if (s != null) {

                            for (int i = 0; i < buyGoods.getData().size(); i++) {

                                BuyData buyData = new BuyData();
                                buyData.name = buyGoods.getData().get(i).getName();
                                buyData.company = buyGoods.getData().get(i).getCompany();
                                buyData.companyId = buyGoods.getData().get(i).getCompanyId();
                                buyData.description = buyGoods.getData().get(i).getDescription();
                                buyData.saleMoney = buyGoods.getData().get(i).getSaleMoney();
                                buyData.img = buyGoods.getData().get(i).getImg();
                                buyData.number = buyGoods.getData().get(i).getNumber();
                                buyData.select = false;
                                buyData.goodid = buyGoods.getData().get(i).getGoodid();
                                Log.i("GoodId的值：",String.valueOf(buyGoods.getData().get(i).getGoodid()));
                                buyData.id = buyGoods.getData().get(i).getId();
                                BuyList.add(buyData);
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    item.setAdapter(myAdapter3);
                                    item.setLayoutManager(new LinearLayoutManager(getActivity()));
                                }
                            });
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
        edit.setOnClickListener(new View.OnClickListener() {//编辑按钮
            @Override
            public void onClick(View v) {
                editLayout.setVisibility(View.VISIBLE);
                submitLayout.setVisibility(View.GONE);
                edit.setVisibility(View.GONE);
                back.setVisibility(View.VISIBLE);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {//退出编辑
            @Override
            public void onClick(View v) {
                editLayout.setVisibility(View.GONE);
                submitLayout.setVisibility(View.VISIBLE);
                edit.setVisibility(View.VISIBLE);
                back.setVisibility(View.GONE);
            }
        });
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i("BuyList的大小：",String.valueOf(size));
                if (isChecked) {
                    for (int i = 0; i < size; i++) {
                        BuyList.get(i).select = true;
                    }
                    myAdapter3.notifyDataSetChanged();
                    item.setAdapter(myAdapter3);
                    Log.i("全选：", "asdfghjklqwertyuiozxcvbnm");
                }
                if (!isChecked){
                    for(int i = 0 ; i<size;i++) {
                        BuyList.get(i).select = false;
                    }
                    myAdapter3.notifyDataSetChanged();
                    Log.i("全不选：","asdfghjklqwertyuiozxcvbnm");
                }
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {//删除购物车里面的商品
            @Override
            public void onClick(View v) {
                index.clear();
                for(int i=size-1;i>=0;i--) {
                    if (BuyList.get(i).select) {
                        index.add(BuyList.get(i).id);

                        Log.i("选中的位置：", String.valueOf(BuyList.get(i)));
                        BuyList.remove(i);
                    }
                }
                Thread thread = new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        for(int i =0 ;i<index.size();i++) {
                            try {
                                String res = post("http://192.168.43.138:8080/index/deleteShopGood/" + index.get(i).intValue());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    myAdapter3.notifyDataSetChanged();
                                    countNum.setText("0");
                                    countPrice.setText("0");
                                    item.setAdapter(myAdapter3);
                                }
                            });
                        }
                    }
                };
                thread.start();
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {//去付款生成订单
            @Override
            public void onClick(View v) {
                index.clear();
                //System.out.println("adsjifhijudas");
                for(int i=size-1;i>=0;i--) {
                    if (BuyList.get(i).select) {//选中的商品
                        index.add(BuyList.get(i).id);
                        Manager.initDB(getActivity());//初始化数据库
                        Manager.addDrug(BuyList.get(i).name,BuyList.get(i).img,BuyList.get(i).description,BuyList.get(i).number,BuyList.get(i).companyId,BuyList.get(i).saleMoney,BuyList.get(i).goodid);
                    }
                }
                Thread thread = new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        for (int i = 0; i < index.size(); i++) {
                            try {
                                post("http://192.168.43.138:8080/index/deleteShopGood/" + index.get(i).intValue());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                thread.start();
                //Log.i("添加商品到订单：",String.valueOf(index.get(0)));
                Toast.makeText(getActivity(),"生成订单",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(),dingdan.class);
                intent.putExtra("number",countNum.getText());
                intent.putExtra("price",countPrice.getText());
                startActivity(intent);
                countNum.setText("0");
                countPrice.setText("0");
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.ASYNC)//子线程
    public void omThread(String event) throws IOException {
        String msg = event;
        Log.i("运行至此处2：", "sdfsdfsdfsdfsd");
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user",getActivity().MODE_PRIVATE);
        token = sharedPreferences.getString("token",null) ;
        Log.i("token值：",token);
        if (msg != null) {
            Log.i("获得的ID值：", String.valueOf(MainActivity.idCode));
            String s = okPost("http://192.168.43.138:8080/index/getShopGood");
            Log.i("购物车请求结果：", s);

            Gson gson = new Gson();
            buyGoods = gson.fromJson(s, BuyGoods.class);
            BuyList.clear();
            if (s != null) {

                for (int i = 0; i < buyGoods.getData().size(); i++) {

                    BuyData buyData = new BuyData();
                    buyData.name = buyGoods.getData().get(i).getName();
                    buyData.company = buyGoods.getData().get(i).getCompany();
                    buyData.companyId = buyGoods.getData().get(i).getCompanyId();
                    buyData.description = buyGoods.getData().get(i).getDescription();
                    buyData.saleMoney = buyGoods.getData().get(i).getSaleMoney();
                    buyData.img = buyGoods.getData().get(i).getImg();
                    buyData.number = buyGoods.getData().get(i).getNumber();
                    buyData.id = buyGoods.getData().get(i).getId();
                    //Log.i("现在的ID：",String.valueOf(buyGoods.getData().get(i).getId()));
                    BuyList.add(buyData);

                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        item.setAdapter(new MyAdapter3());
                        int space = 4;
                        item.addItemDecoration(new SpacesItemDecoration(space));
                        item.setLayoutManager(new LinearLayoutManager(getActivity()));
                    }
                });
            }
        }
        Log.d("harvic", msg);

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    private void init() {//初始化控件
        item = getActivity().findViewById(R.id.recyclerView);
        submit = getActivity().findViewById(R.id.constraintLayout40);
        countNum = getActivity().findViewById(R.id.count1);
        countPrice = getActivity().findViewById(R.id.count);
        edit = getActivity().findViewById(R.id.edit);
        editLayout = getActivity().findViewById(R.id.constraintLayout5);
        submitLayout = getActivity().findViewById(R.id.constraintLayout2);
        delete = getActivity().findViewById(R.id.delete);
        back = getActivity().findViewById(R.id.back);
        checkBox= getActivity().findViewById(R.id.checkBox2);
    }


    public class MyAdapter3 extends RecyclerView.Adapter<MyHolder3> {//RecyclerView适配器

        @NonNull
        @Override
        public MyHolder3 onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.buy_item, parent, false);
            MyHolder3 myHolder3 = new MyHolder3(view);
            return myHolder3;
        }

        @Override
        public void onBindViewHolder(@NonNull final MyHolder3 holder,final int position) {
            size = BuyList.size();
            Glide.with(getActivity()).load(String.valueOf(BuyList.get(position).img)).into(holder.img);
            Log.i("size：",String.valueOf(size));
            holder.bread.setText(" "+ BuyList.get(position).company+" ");
            holder.describe.setText(BuyList.get(position).description);
            holder.price.setText(String.valueOf(BuyList.get(position).saleMoney));
            holder.name.setText(BuyList.get(position).name);
            holder.count.setText(String.valueOf(BuyList.get(position).number));
            holder.select.setChecked(BuyList.get(position).select);
            //Log.i("是否选中状态：", String.valueOf(BuyList.get(position).select));
            //holder.bread.setText(BuyList.get(position).company);
            holder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//增加商品数量-》需求：取消选中状态，此时购买栏减去对应的数量和价格
                    holder.count.setText(String.valueOf(Integer.valueOf(holder.count.getText().toString()) + 1));

                    if (holder.select.isChecked()){
                        holder.select.setChecked(false);//改变数量就取消选中
                        BuyList.get(position).select = false;
                        countNum.setText(String.valueOf(Integer.valueOf(countNum.getText().toString())-1));
                        countPrice.setText(String.valueOf(Double.valueOf(countPrice.getText().toString())-Double.valueOf(holder.price.getText().toString())));
                    }
                }
            });
            holder.sub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//减少商品数量
                    if(Integer.valueOf(holder.count.getText().toString()) >=2 ){//商品数量大于1
                        holder.count.setText(String.valueOf(Integer.valueOf(holder.count.getText().toString()) - 1));
                        if (holder.select.isChecked()){
                            holder.select.setChecked(false);//改变数量就取消选中
                            BuyList.get(position).select = false;
                            countNum.setText(String.valueOf(Integer.valueOf(countNum.getText().toString())-1));
                            countPrice.setText(String.valueOf(Double.valueOf(countPrice.getText().toString())-Double.valueOf(holder.price.getText().toString())));
                        }
                    }else{
                        Toast.makeText(getActivity(),"数量不能小于1",Toast.LENGTH_SHORT).show();
                    }
                }
            });
            holder.select.setOnClickListener(new View.OnClickListener() {//复选框点击监听
                @Override
                public void onClick(View v) {
                    if(holder.select.isChecked()){//已选状态
                        //countNum.setText("0");
                        //数量变动
                        BuyList.get(position).select = true;
                        String oddNumString = countNum.getText().toString();
                        int oddNum = Integer.valueOf(oddNumString);
                        int newNum = 1 ;//Integer.valueOf(holder.count.getText().toString());
                        countNum.setText(String.valueOf(oddNum + newNum));

                        //价格变动
                        Double oddPrice = Double.valueOf(countPrice.getText().toString());
                        Double newPrice = Double.valueOf(holder.price.getText().toString()) * Integer.valueOf(holder.count.getText().toString());
                        countPrice.setText(String.valueOf(oddPrice + newPrice));
                    }else{//未选状态
                        //countNum.setText("0");
                        //数量变动
                        BuyList.get(position).select = false;
                        String oddNumString = countNum.getText().toString();
                        int oddNum = Integer.valueOf(oddNumString);
                        int newNum = 1;//Integer.valueOf(holder.count.getText().toString());
                        countNum.setText(String.valueOf(oddNum - newNum));
                        //价格变动
                        String oddPriceString =countPrice.getText().toString();
                        Double oddPrice = Double.valueOf(oddPriceString);
                        Double newPrice = Double.valueOf(holder.price.getText().toString()) * Integer.valueOf(holder.count.getText().toString());
                        countPrice.setText(String.valueOf(oddPrice - newPrice));
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return BuyList.size();
        }
    }

    public class MyHolder3 extends RecyclerView.ViewHolder {

        TextView bread, describe, name, price, count, add, sub;
        CheckBox select;
        ImageView img;

        public MyHolder3(@NonNull View itemView) {
            super(itemView);
            bread = itemView.findViewById(R.id.textView8);
            describe = itemView.findViewById(R.id.textView10);
            name = itemView.findViewById(R.id.name);
            price = itemView.findViewById(R.id.textView12);
            count = itemView.findViewById(R.id.textView14);
            add = itemView.findViewById(R.id.textView13);
            sub = itemView.findViewById(R.id.sub);
            select = itemView.findViewById(R.id.checkBox);
            img = itemView.findViewById(R.id.imageView4);
        }
    }

    /**
     * OkHttp网络请求 post调用带Token
     */
    public String okPost(String url) throws IOException {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        if (token != null) {
            RequestBody body = RequestBody.create(JSON, "1");
            final Request request = new Request.Builder()
                    .url(url)
                    .addHeader("authorization", token)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                res = response.body().string();
                Log.i("返回购物车结果：", res);
                return res;
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
        return res;
    }
    //不带token
    public String post (String url) throws IOException{
        RequestBody body = RequestBody.create(MediaType.parse("application/json"),"1");
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String res = response.body().string();
            Log.i("返回删除结果：", res);
            return res;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }
}